package com.oj.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oj.config.OAuthConfig;
import com.oj.entity.OAuth;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GithubOAuth {
    public String getToken(String client_id, String client_secret, String code){
        try {
            String url = "https://github.com/login/oauth/access_token" ;
            url += "?code="+code;
            url += "&client_id="+client_id;
            url += "&client_secret="+client_secret;
            log.info("github login: client_id="+client_id+"&client_secret="+client_secret+"&code="+code);
            Map<String,String> headers = new HashMap<>(1,1);
            headers.put("accept", "application/json");
            JSONObject paramJson = new JSONObject();
            String json = HttpClientUtil.doPost(url, paramJson, headers);
            //{"access_token":"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","token_type":"bearer","scope":""}
            Map map = (Map)JSON.parse(json);
            //access_token=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&scope=&token_type=bearer
            return map.get("access_token").toString();
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }
    public OAuth getUserInfo(String token) {
        try {
            String url = "https://api.github.com/user";
            Map<String,String> headers = new HashMap<>(1,1);
            headers.put("accept", "application/json");
            headers.put("Authorization", "token "+token);
            String json = HttpClientUtil.doGet(url, headers);
            Map map = (Map)JSON.parse(json);
            OAuth oauth = new OAuth();
            oauth.setProvider("github");
            oauth.setLogin(map.get("login").toString());
            oauth.setNickname(map.get("name").toString());
            oauth.setAvatar_url(map.get("avatar_url").toString());
            return oauth;
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }
    public OAuth login(String client_id, String client_secret, String code){
        String token = getToken(client_id, client_secret, code);
        if (token == null) {
            return null;
        }
        return getUserInfo(token);
    }

    public static void main(String[] args){
        GithubOAuth github = new GithubOAuth();
        // https://github.com/login/oauth/authorize?client_id=1e4854a69a833e13c195
        //github.login("1e4854a69a833e13c195","0fc4a364989d19d9ad9e326e8d10f23e9e10d171 ","50f766c5a8249a1c0fe8");
        //main.test2();
    }
}
